﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using _DataProvider;
using ServiceConsumer;

public partial class Admin_Parts_MuaHangNXB : System.Web.UI.UserControl
{
    private SqlConnection connSql;
    //private Soap.ServiceSoapClient ws = new Soap.ServiceSoapClient();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["SID"] = "";
            DataSet ds1 = loadnxb();
            drlnxb.DataTextField = "ProviderName";
            drlnxb.DataValueField = "ProviderID";
            drlnxb.DataSource = ds1.Tables[0];

            drlnxb.DataBind();
        }
        
        //GridView1.DataSource = ds1.Tables[0];
        //GridView1.DataBind();
    }

    public DataSet loadnxb()
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        SqlDataAdapter daDepart = null;
        daDepart = new SqlDataAdapter("SELECT * FROM NhaCungCap", connSql);
        DataSet ds = new DataSet();
        daDepart.Fill(ds);
        return ds;
    }

    public DataSet loaddmc()
    {
        DataSet ds = new DataSet();
        if (Session["SID"].ToString() != "-1" && Session["SID"].ToString() != "")
        {
            DataProvider dt = new DataProvider();
            connSql = dt.connect();
            SqlDataAdapter daDepart = null;
            daDepart = new SqlDataAdapter("SELECT * FROM DanhMucCha", connSql);

            daDepart.Fill(ds);

        }
        return ds;
    }

    public DataSet loadinfoconnect(String ProviderID)
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        SqlDataAdapter daDepart = null;
        daDepart = new SqlDataAdapter("SELECT * FROM NhaCungCap where ProviderID='" + ProviderID + "'", connSql);
        DataSet ds = new DataSet();
        daDepart.Fill(ds);
        return ds;
    }


    protected void btnketnoi_Click(object sender, EventArgs e)
    {
        DataSet ds = loadinfoconnect(drlnxb.SelectedValue.ToString());
        DataRow dr = ds.Tables[0].Rows[0];
        Session["NXB"] = dr;

        object result = WSProxy.CallWebService(dr["LinkWS"].ToString(), "Service", "WSLogin", new object[] { dr["PartnerID"].ToString(), dr["PartnerPwd"].ToString() });

        //object result = ws.WSLogin(dr["PartnerID"].ToString(), dr["PartnerPwd"].ToString());
        result = ChangeType(result, "String");
        Session["SID"] = result.ToString();
        if (Session["SID"].ToString() != "-1" && Session["SID"].ToString() != "")
        {
            Response.Write("<script> alert('Kết nối thành công') </script>");
        }
        else
        {
            Response.Write("<script> alert('Kết nối thất bại') </script>");
        }
        Label4.Visible = true;
        drldmc.Visible = true;

        DataSet ds1 = loaddmc();
        drldmc.DataTextField = "ParentCatName";
        drldmc.DataValueField = "ParentCatID";
        drldmc.DataSource = ds1.Tables[0];
        //drldmc.SelectedIndex = 1;
        drldmc.DataBind();
    }
    
    public object ChangeType(object ob, String str)
    {
        if (str == "String")
            ob = Convert.ChangeType(ob, typeof(String));
        if (str == "Int")
            ob = Convert.ChangeType(ob, typeof(Int32));
        if (str == "Boolean")
            ob = Convert.ChangeType(ob, typeof(Boolean));
        if (str == "Float")
            ob = Convert.ChangeType(ob, typeof(float));
        if (str == "Data")
            ob = Convert.ChangeType(ob, typeof(DataTable));
        return ob;
    }

    protected void drldm_SelectedIndexChanged(object sender, EventArgs e)
    {
        btndangky.Visible = true;
        String str = drldm.SelectedValue.ToString().Trim();
        //str = "";
        DataRow dr = (DataRow)Session["NXB"];
        object result1 = WSProxy.CallWebService(dr["LinkWS"].ToString(), "Service", "Product", new object[] { str });
        //object result1 = ws.Product(str);
        result1 = ChangeType(result1, "Data");
        //DataTable dt = result;
        GridView1.DataSource = result1;
        GridView1.DataBind();
        drldm.SelectedValue = str;
    }

    protected void drldmc_SelectedIndexChanged(object sender, EventArgs e)
    {
        String str = drldmc.SelectedValue.ToString();
        String SID = "";
        SID = Session["SID"].ToString();
        if (SID != "-1" && SID != "")
        {
            DataRow dr = (DataRow)Session["NXB"];
            object result1 = WSProxy.CallWebService(dr["LinkWS"].ToString(), "Service", "Category", new object[] { str });
            //object result1 = ws.Category(str);
            result1 = ChangeType(result1, "Data");
            drldm.DataTextField = "CatName";
            drldm.DataValueField = "CatId";

            drldm.DataSource = result1;

            drldm.DataBind();
            //drldm.SelectedValue = "1";
        }
        else if (SID == "-1" || SID == "")
        {
            Response.Write("<script>alert('Chưa kết nối')</script>");
        }
        drldmc.SelectedValue = str;
        Label3.Visible = true;
        drldm.Visible = true;
    }

    protected void btndangky_Click(object sender, EventArgs e)
    {
        if (GridView1.SelectedIndex == -1)
        {
            Response.Write("<script>alert('Chọn sản phẩm cần đăng ký')</script>");
        }
        else
        {
            Panel1.Visible = true;
            GridViewRow gr = GridView1.SelectedRow;
            Boolean kq = InsertProduct(gr);
            if (kq == false)
            {
                Response.Write("<script>alert('Sản phẩm đã được đăng ký')</script>");
            }
            txtid.Text = gr.Cells[1].Text;
            //txtid.Visible = kq; 
        }
    }

    public Boolean InsertProduct(GridViewRow gr)
    {
        try
        {
            TextBox txtimages = (TextBox)(gr.FindControl("TextBox1"));
            String query = "INSERT INTO TaiLieu(ProductID,ProductName,ProductPrice,ProductQuantity,"
            + "ProductPhotoURL,ProductDescription,CatID,Dimension,DateAdd,State) "
            + "VALUES ('" + int.Parse(gr.Cells[1].Text) + "','" + gr.Cells[2].Text + "',"
            + "'" + float.Parse(gr.Cells[3].Text) + "','0',"
            + "'" + txtimages.Text + "','" + gr.Cells[5].Text + "','" + drldm.SelectedValue + "',"
            + "'" + gr.Cells[8].Text + "','" + DateTime.Now.ToShortDateString() + "','-1')";
            //String querygd = "INSERT INTO GiaoDich(SessionID,ProductID,ProviderID,State) "
            //                + "VALUES ('" + SID + "', "
            //                + Int32.Parse(dr["ProductID"].ToString()) + ", "
            //                 + "'" + ProviderID + "','0')";
            DataProvider dtp = new DataProvider();
            connSql = dtp.connect();
            dtp.executeNonQuery(query);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public int GetLastID()
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        string sql = "SELECT TOP 1 TransID FROM GiaoDich ORDER BY TransID DESC";
        int kq = (int)dt.executeScalar(sql);

        return kq;
    }
    
    protected void btnchapnhan_Click(object sender, EventArgs e)
    {

        if (Session["TransID"] == null)
        {
            Session["TransID"] = GetLastID();
        }

        DataTable dt = (DataTable)Session["Data"];

        if (dt == null)
        {
            dt = new DataTable("MyTable");
            dt.Columns.Add("TransID");
            dt.Columns.Add("ProductID");

            dt.Columns.Add("MinQuantity");

            dt.Columns.Add("NextTransQuantity");

            dt.Columns.Add("BeginTransDate");

            dt.Columns.Add("EndTransDate");
        }
        DataRow dr = dt.NewRow();
        int TransID = (int)Session["TransID"] + 1;

        dr["TransID"] = TransID;
        Session["TransID"] = TransID;
        dr["ProductID"] = txtid.Text;
        dr["MinQuantity"] = txtminq.Text;
        dr["NextTransQuantity"] = txtnextq.Text;
        dr["BeginTransDate"] = Calendar1.SelectedDate;
        dr["EndTransDate"] = Calendar2.SelectedDate;
        dt.Rows.Add(dr);

        //dt.LoadDataRow(new object[]{txtid.Text, txtminq.Text, txtnextq.Text, Calendar1.SelectedDate,Calendar2.SelectedDate});
        Session["Data"] = dt;
        grv.DataSource = dt;

        grv.DataBind();
        Panel1.Visible = false;
        Panel2.Visible = true;
    }
    
    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        DataTable dt = (DataTable)Session["Data"];
        grv.EditIndex = e.NewEditIndex;
        //GridView1.DataBind();
        grv.DataSource = dt;

        grv.DataBind();
    }

    protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        DataTable dt = (DataTable)Session["Data"];
        grv.EditIndex = -1;
        grv.DataSource = dt;

        grv.DataBind();
    }

    protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DataTable dt2 = (DataTable)Session["Data"];

        //Update the values.
        GridViewRow row = grv.Rows[e.RowIndex];

        //dt.Rows[row.DataItemIndex]["ProductID"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
        dt2.Rows[row.DataItemIndex]["MinQuantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
        dt2.Rows[row.DataItemIndex]["NextTransQuantity"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
        dt2.Rows[row.DataItemIndex]["BeginTransDate"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
        dt2.Rows[row.DataItemIndex]["EndTransDate"] = ((TextBox)(row.Cells[5].Controls[0])).Text;

        //Reset the edit index.
        grv.EditIndex = -1;
        grv.DataSource = dt2;

        grv.DataBind();
    }

    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv.PageIndex = e.NewPageIndex;
        DataTable dt = (DataTable)Session["Data"];

        //GridView1.DataBind();
        grv.DataSource = dt;

        grv.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)Session["Data"];
        DataRow dr = (DataRow)Session["NXB"];
        object result1 = WSProxy.CallWebService(dr["LinkWS"].ToString(), "Service", "RegisterTrans", new object[] { Session["SID"].ToString(), dt });

        //System.Net.CookieContainer container = new System.Net.CookieContainer();
        //.CookieContainer = new System.Net.CookieContainer();

        //object result1 = ws.RegisterTrans(Session["SID"].ToString(), dt);

        result1 = ChangeType(result1, "String");
        if (result1.ToString() == "0")
        {
            Response.Write("<script>alert('Đã gửi giao dịch thành công')</script>");
            InsertTrans(Session["SID"].ToString(), dt, dr["ProviderID"].ToString());
        }
        else if (result1.ToString() == "-1")
        {
            Response.Write("<script>alert('Thất bại do chưa kết nối')</script>");
        }
        else
        {
            Response.Write("<script>alert('Thất bại do không cập nhật được dữ liệu tới nhà xuất bản')</script>");
        }
        Session["Data"] = null;
        Session["TransID"] = null;
        Panel2.Visible = false;
        //Response.Redirect("~/admin//MuaHang_NXB.aspx");
    }

    public Boolean InsertTrans(String SID, DataTable dt, String ProviderID)
    {

        //DateTime date = DateTime.Now;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            try
            {
                DataRow dr = dt.Rows[i];
                String querygd = "INSERT INTO GiaoDich(TransID,SessionID,ProductID,ProviderID,State) "
                        + "VALUES (" + Int32.Parse(dr["TransID"].ToString()) + ",'" + SID + "', "
                        + Int32.Parse(dr["ProductID"].ToString()) + ", "
                         + "'" + ProviderID + "','0')";

                String queryspht = "INSERT INTO SanPhamHopTac(TransID,ProductID,MinQuantity,NextTransQuantity,"
                        + "BeginTransDate,EndTransDate,ProviderID) "
                        + "VALUES (" + Int32.Parse(dr["TransID"].ToString()) + "," + Int32.Parse(dr["ProductID"].ToString()) + "," + Int32.Parse(dr["MinQuantity"].ToString()) + ", "
                        + Int32.Parse(dr["NextTransQuantity"].ToString()) + ", '" + dr["BeginTransDate"] + "', '"
                        + dr["EndTransDate"] + "', '" + ProviderID + "')";


                //String query = "INSERT INTO GiaoDich(SessionID,ProductID, MinQuantity, NextTransQuantity, " +
                //        "BeginTransDate, EndTransDate, ProviderID,State) "
                //+ "VALUES ('" + SID + "', "
                //+ Int32.Parse(dr["ProductID"].ToString()) + "," + Int32.Parse(dr["MinQuantity"].ToString()) + ", "
                //+ Int32.Parse(dr["NextTransQuantity"].ToString()) + ", '" + dr["BeginTransDate"] + "', '"
                //+ dr["EndTransDate"] + "', '" + ProviderID + "',0)";
                DataProvider dtp = new DataProvider();
                connSql = dtp.connect();
                dtp.executeNonQuery(querygd);
                dtp.executeNonQuery(queryspht);
            }
            catch (Exception)
            {
                return false;
            }
        }

        return true;
    }
    
    protected void grv_RowDeleting2(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dt1 = (DataTable)Session["Data"];
        //grv.DeleteRow(e.RowIndex);
        dt1.Rows.RemoveAt(e.RowIndex);
        //GridView1.DataBind();
        grv.DataSource = dt1;

        grv.DataBind();
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        this.Calendar1.Visible = !this.Calendar1.Visible;

    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        this.Calendar2.Visible = !this.Calendar1.Visible;
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        this.TextBox3.Text = Calendar1.SelectedDate.ToShortDateString();
        this.Calendar1.Visible = false;
    }
    protected void Calendar2_SelectionChanged(object sender, EventArgs e)
    {
        this.TextBox4.Text = Calendar1.SelectedDate.ToShortDateString();
        this.Calendar2.Visible = false;
    }
}